package org.jeecg.modules.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.system.entity.BizEquipmentEntity;
import org.jeecg.modules.system.entity.BizEquipmentStateEntity;
import org.jeecg.modules.system.entity.BizSiteEntity;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.IBizEquipmentService;
import org.jeecg.modules.system.service.IBizSiteService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.system.service.impl.SysDictServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Slf4j
@RestController
@RequestMapping("/biz/equipment")
@Api(tags="设备管理")
public class BizEquipmentController {

    @Autowired
    private IBizEquipmentService bizEquipmentService;

    @Autowired
    private IBizSiteService bizSiteService;

    @Autowired
    private SysDictServiceImpl sysDictService;

    @Autowired
    private ISysUserService sysUserService;

    @ApiOperation(value = "查询设备", notes = "查询设备-列表分页查询")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result<IPage<BizEquipmentEntity>> queryPageList(BizEquipmentEntity bizEquipmentEntity, @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                           @RequestParam(name="pageSize", defaultValue="10") Integer pageSize, HttpServletRequest req) {
        String username = JwtUtil.getUserNameByToken(req);
        Set<String> roles = sysUserService.getUserRolesSet(username);
        String roleStr = String.join(", ", roles);

        SysUser sysUser = sysUserService.getUserByName(username);

        Result<IPage<BizEquipmentEntity>> result = new Result<IPage<BizEquipmentEntity>>();
        QueryWrapper<BizEquipmentEntity> queryWrapper = QueryGenerator.initQueryWrapper(bizEquipmentEntity, req.getParameterMap());


        if(!roleStr.contains("admin") & !roleStr.contains("system")){
            queryWrapper.inSql("site_id","select site_id from biz_site_user where user_id='"+sysUser.getId()+"'");
        }

        queryWrapper.orderByAsc("create_time");
        Page<BizEquipmentEntity> page = new Page<BizEquipmentEntity>(pageNo, pageSize);
        IPage<BizEquipmentEntity> pageList = bizEquipmentService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    @ApiOperation(value = "新增设备", notes = "新增设备")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result<BizEquipmentEntity> add(@RequestBody BizEquipmentEntity bizEquipmentEntity, HttpServletRequest request) {
        Result<BizEquipmentEntity> result = new Result<BizEquipmentEntity>();

        String username = JwtUtil.getUserNameByToken(request);
        try {
            //与存在eq_code不允许添加
            QueryWrapper<BizEquipmentEntity> queryWrapper = new QueryWrapper();
            queryWrapper.eq("eq_code",bizEquipmentEntity.getEqCode());

            BizEquipmentEntity bizEquipmentOriginal = bizEquipmentService.getOne(queryWrapper);
            if(bizEquipmentOriginal!=null){
                result.error500("已存在eq_code["+bizEquipmentOriginal.getEqCode()+"]");
                return result;
            }

            //校验
            Result<BizEquipmentEntity> check = new Result<BizEquipmentEntity>();
            check = checkRule(bizEquipmentEntity);
            if(!check.isSuccess()) return check;

            bizEquipmentEntity.setCreateTime(DateUtils.getTimestamp());
            bizEquipmentEntity.setCreatorId(username);
            bizEquipmentService.save(bizEquipmentEntity);
            result.success("保存成功！");
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            result.error500("操作失败");
        }
        return result;
    }


    @ApiOperation(value = "编辑设备", notes = "编辑设备")
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Result<BizEquipmentEntity> edit(@RequestBody BizEquipmentEntity bizEquipmentEntity,HttpServletRequest request) {
        Result<BizEquipmentEntity> result = new Result<BizEquipmentEntity>();
        String username = JwtUtil.getUserNameByToken(request);

        BizEquipmentEntity bizequipmentOriginal = bizEquipmentService.getById((Serializable) bizEquipmentEntity.getEqId());
        if(bizequipmentOriginal==null) {
            result.error500("未找到对应实体");
        }else {

//            Result<BizEquipmentEntity> check = new Result<BizEquipmentEntity>();
//            check = checkRule(bizEquipmentEntity);
//            if(!check.isSuccess()) return check;

            bizEquipmentEntity.setModifyTime(DateUtils.getTimestamp());
            bizEquipmentEntity.setModifierId(username);
            boolean ok = bizEquipmentService.updateById(bizEquipmentEntity);
            if(ok) {
                result.success("编辑成功!");
            }
        }
        return result;
    }

    private Result<BizEquipmentEntity> checkRule(BizEquipmentEntity bizEquipmentEntity){
        Result<org.jeecg.modules.system.entity.BizEquipmentEntity> result = new Result<org.jeecg.modules.system.entity.BizEquipmentEntity>();

//        if(StringUtils.isEmpty(bizEquipmentEntity.getDtuId())){
//            result.error500("dtuId不能为空");
//            return result;
//        }

        if(bizEquipmentEntity.getEqType() ==  null){
            result.error500("eqType不能为空");
            return result;
        }else {
            if(StringUtils.isEmpty(sysDictService.queryDictTextByKey("dict_eq_type",bizEquipmentEntity.getEqType()+""))){
                result.error500("eqType未在字典【dict_eq_type】中匹配");
                return result;
            }
        }

//        if(bizEquipmentEntity.getElectType() ==  null){
//            result.error500("electType不能为空");
//            return result;
//        }else {
//            if(StringUtils.isEmpty(sysDictService.queryDictTextByKey("dict_elect_type",bizEquipmentEntity.getElectType()+""))){
//                result.error500("electType未在字典【dict_elect_type】中匹配");
//                return result;
//            }
//        }


        QueryWrapper<BizSiteEntity> querySiteCountWrapper = new QueryWrapper();
        querySiteCountWrapper.eq("site_id",bizEquipmentEntity.getSiteId());
        long siteCount =  bizSiteService.count(querySiteCountWrapper);
        if(siteCount == 0){
            result.error500("不存在站点id["+bizEquipmentEntity.getSiteId()+"]");
            return result;
        }

        result.success("校验成功!");
        return result;
    }

    @ApiOperation(value = "查询不同状态的设备数量", notes = "查询设备状态数-在线状态：0 设备初始化  1 设备在线  2 设备离线（从未上线）  3 设备掉线  4 设备暂停")
    @RequestMapping(value = "/listStatusCount", method = RequestMethod.GET)
    public Result<List<Map<?,?>>> listStatusCount(@RequestParam(name="siteId",required = false) String siteId,HttpServletRequest req) {
        Result<List<Map<?,?>>> result = new Result<List<Map<?,?>>>();
        result.setResult(bizEquipmentService.getStatusCount(siteId));
        result.success("查询成功!");
        return result;
    }


    @ApiOperation(value = "根据权限查询设备", notes = "查询设备-列表分页查询")
    @RequestMapping(value = "/listByUser", method = RequestMethod.GET)
    public Result<IPage<BizEquipmentEntity>> querySitePageListByUser(BizEquipmentEntity bizEquipmentEntity, @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                                @RequestParam(name="pageSize", defaultValue="10") Integer pageSize, String userId ,HttpServletRequest req) {
        Result<IPage<BizEquipmentEntity>> result = new Result<IPage<BizEquipmentEntity>>();

        QueryWrapper<BizEquipmentEntity> queryWrapper = new QueryWrapper<BizEquipmentEntity>();
//        if(StringUtils.isEmpty(userId)) {
//            String username = JwtUtil.getUserNameByToken(req);
//            SysUser sysUser = sysUserService.getUserByName(username);
//            userId = sysUser.getId();
//        }

        queryWrapper.inSql("site_id","select site_id from biz_site_user a where a.status=1 and a.user_id='"+userId+"'");
        
        
        if(StringUtils.isNotEmpty(bizEquipmentEntity.getSiteId())){
            queryWrapper.eq("site_id",bizEquipmentEntity.getSiteId());
        }

        if(StringUtils.isNotEmpty(bizEquipmentEntity.getEqType()+"")){
            queryWrapper.eq("eq_type",bizEquipmentEntity.getEqType());
        }

        if(StringUtils.isNotEmpty(bizEquipmentEntity.getEqCode()+"")){
            queryWrapper.eq("eq_code",bizEquipmentEntity.getEqCode());
        }

        if(StringUtils.isNotEmpty(bizEquipmentEntity.getCompany()+"")){
            queryWrapper.like("company",bizEquipmentEntity.getCompany());
        }

        if(bizEquipmentEntity.getStatus()!=null){
            queryWrapper.eq("status",bizEquipmentEntity.getStatus());
        }
        
        Page<BizEquipmentEntity> page = new Page<BizEquipmentEntity>(pageNo, pageSize);
        IPage<BizEquipmentEntity> pageList = bizEquipmentService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

}
